'use client';

import { useState, useEffect, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { VmsCopy } from '@/types/Model'
import TailwindAdvancedEditor from "@/components/tailwind/advanced-editor"
import { toast } from '@/hooks/use-toast'
import { Skeleton } from "@/components/ui/skeleton";
import NotionSidebar from '@/components/notion/NotionSidebar';
import { DragDropContext, Droppable, Draggable, DropResult } from '@hello-pangea/dnd';
import { Breadcrumb, BreadcrumbItem, BreadcrumbLink,BreadcrumbSeparator,BreadcrumbList } from "@/components/ui/breadcrumb";
import { Slash } from 'lucide-react';

interface Copy {
  id: string;
  title: string;
  pxh: number;
}

interface Topic {
  id: string;
  name: string;
  pxh: number;
  copies: Copy[];
}

// 提取使用 useSearchParams 的组件
function NotionPageContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const topicIdFromUrl = searchParams.get('topicid');
  // 搜索用
  const [searchDialogOpen, setSearchDialogOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [searchResults, setSearchResults] = useState<Array<{topic: Topic, copy: Copy}>>([]);
  // copy 数据
  const [copy, setCopy] = useState<VmsCopy | undefined>(undefined)
  const [copyLoading, setCopyLoading] = useState(false)
  // topic 数据
  const [expandedTopics, setExpandedTopics] = useState<Record<string, boolean>>({});
  const [selectedItem, setSelectedItem] = useState<{
    type: 'topic' | 'copy';
    topicId: string;
    copyId?: string;
  } | null>(null);

  const [filteredTopics, setFilteredTopics] = useState<Topic[]>([]);

  const [topics, setTopics] = useState<Topic[]>([
    {
      id: 'topic1',
      name: '工作',
      pxh: 1,
      copies: [
        { id: 'copy1', title: '项目计划', pxh: 1 },
        { id: 'copy2', title: '会议记录', pxh: 2 }
      ]
    },
    {
      id: 'topic2',
      name: '个人',
      pxh: 2,
      copies: [
        { id: 'copy3', title: '读书笔记', pxh: 1 },
        { id: 'copy4', title: '旅行计划', pxh: 2 }
      ]
    }
  ]);


  // 添加搜索处理函数
  const handleSearch = (term: string) => {
    setSearchTerm(term);
    const results: Array<{topic: Topic, copy: Copy}> = [];
    
    topics.forEach(topic => {
      topic.copies.forEach(copy => {
        if (copy.title.toLowerCase().includes(term.toLowerCase())) {
          results.push({ topic, copy });
        }
      });
    });
    
    setSearchResults(results);
  };

    // 添加topic加载状态
    const [loading, setLoading] = useState(true);

    const fetchCopy = async (id: String, topicId?: string) => {
      // 添加安全检查：确保要获取的文案在当前topics中存在
      const copyExists = topics.some(topic => 
        topic.copies.some(copy => copy.id === id)
      );
      
      if (!copyExists) {
        console.warn(`Copy ${id} not found in current topics, skipping fetch`);
        return;
      }
      
      setCopyLoading(true)
      try {
        const token = localStorage.getItem('token')
        const response = await fetch(`/api/copy/${id}`, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (!response.ok) {
          throw new Error('Failed to fetch copy details')
        }
        
        const data = await response.json()
        // 在设置新内容前再次清除旧内容
        localStorage.removeItem("novel-content");
        if(data.content){
          localStorage.setItem("novel-content", JSON.stringify(data.content))
        }
        setCopy(data)
        // 设置选中状态和展开状态
        const tid = topicId || data.topic_id;
        setSelectedItem({ 
          type: 'copy', 
          topicId: tid, 
          copyId: id as string 
        });
        setExpandedTopics(prev => ({
          ...prev,
          [tid]: true
        }));
        toast({
          title: '数据获取成功',
          description: '文案详情已加载',
        })
      } catch (error) {
        console.error('Error fetching copy:', error)
        // 如果获取失败，清理相关的localStorage缓存
        const lastViewed = localStorage.getItem('lastViewedCopy');
        if (lastViewed) {
          try {
            const { copyId } = JSON.parse(lastViewed);
            if (copyId === id) {
              localStorage.removeItem('lastViewedCopy');
              localStorage.removeItem('novel-content');
              localStorage.removeItem('html-content');
              localStorage.removeItem('markdown');
            }
          } catch (parseError) {
            localStorage.removeItem('lastViewedCopy');
          }
        }
        
        toast({
          title: '获取文案失败',
          description: '该文案可能已被删除',
          variant: 'destructive'
        })
      } finally {
        setCopyLoading(false)
      }
    }

    const saveCopy = async (copy: VmsCopy) => {
      try {
        const token = localStorage.getItem('token')
        const response = await fetch(`/api/copy`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(copy)
        })
        
        if (!response.ok) {
          throw new Error('Failed to save copy')
        }
        
        toast({
          title: '保存成功',
          description: '文案已成功保存',
        })
        // 返回值保存更新到topics
        const data = await response.json();
        // 更新 topics 中对应的 copy
        const updatedTopics = topics.map(topic => {
          if (topic.id === data.topic_id) {
            const copyIndex = topic.copies.findIndex(c => c.id === data.id);
            const newCopies = [...topic.copies];
            
            if (copyIndex >= 0) {
              // 如果已存在，更新它
              newCopies[copyIndex] = {
                id: data.id,
                title: data.title,
                pxh: data.pxh
              };
            }
            
            return {
              ...topic,
              copies: newCopies
            };
          }
          return topic;
        });
        
        setTopics(updatedTopics);

   
      } catch (error) {
        console.error('Error saving copy:', error)
        toast({
          title: '保存失败',
          description: error instanceof Error ? error.message : '未知错误',
          variant: 'destructive'
        })
      }
    }

    // 添加获取数据的函数
const fetchTopics = async () => {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch('/api/notion', {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    });

    if (!response.ok) {
      if (response.status === 401) {
        router.push('/login');
        toast({
          title: '登录信息过期',
          description: '请重新登录',
          variant: 'destructive'
        });
        localStorage.clear();
        return;
      }
      throw new Error('获取数据失败');
    }

    const data = await response.json();
    setTopics(data);
    
    // 根据URL参数过滤topics
    let topicsToShow = data;
    if (topicIdFromUrl) {
      topicsToShow = data.filter((topic: Topic) => topic.id === topicIdFromUrl);
      if (topicsToShow.length === 0) {
        toast({
          title: '主题不存在',
          description: '指定的主题ID不存在',
          variant: 'destructive'
        });
        // 如果指定的主题不存在，显示所有主题
        topicsToShow = data;
      }
    }
    setFilteredTopics(topicsToShow);
    
    // 处理文案选择逻辑
    if (topicIdFromUrl && topicsToShow.length > 0) {
      const targetTopic = topicsToShow[0];
      
      // 首先检查localStorage中是否有该主题的记忆内容
      const lastViewed = localStorage.getItem('lastViewedCopy');
      let shouldLoadFromMemory = false;
      
      if (lastViewed) {
        try {
          const { topicId, copyId } = JSON.parse(lastViewed);
          
          // 验证记忆的文案是否属于当前主题且仍然存在
          if (topicId === topicIdFromUrl) {
            const copyExists = targetTopic.copies.some((copy: Copy) => copy.id === copyId);
            if (copyExists) {
              fetchCopy(copyId, topicId);
              shouldLoadFromMemory = true;
            }
          }
        } catch (error) {
          localStorage.removeItem('lastViewedCopy');
        }
      }
      
      // 如果没有记忆内容或记忆内容无效，选择第一个文案
      if (!shouldLoadFromMemory) {
        if (targetTopic.copies.length > 0) {
          fetchCopy(targetTopic.copies[0].id, targetTopic.id);
        } else {
          // 如果没有文案，清空当前显示
          setCopy(undefined);
          setSelectedItem({ type: 'topic', topicId: targetTopic.id });
          setExpandedTopics(prev => ({
            ...prev,
            [targetTopic.id]: true
          }));
        }
      }
    } else {
      // 原有的逻辑：没有指定topicId时的处理
      const lastViewed = localStorage.getItem('lastViewedCopy');
      if (lastViewed) {
        try {
          const { topicId, copyId } = JSON.parse(lastViewed);
          
          const copyExists = data.some((topic: Topic) => 
            topic.id === topicId && topic.copies.some((copy: Copy) => copy.id === copyId)
          );
          
          if (copyExists) {
            fetchCopy(copyId, topicId);
          } else {
            localStorage.removeItem('lastViewedCopy');
          }
        } catch (error) {
          localStorage.removeItem('lastViewedCopy');
        }
      } else if (data.length > 0 && data[0].copies.length > 0) {
        fetchCopy(data[0].copies[0].id, data[0].id);
      }
    }
  } catch (error) {
    console.error('获取话题失败:', error);
    toast({
      title: '获取数据失败',
      description: '请稍后重试',
      variant: 'destructive'
    });
  } finally {
    setLoading(false);
  }
};
  
    // 组件加载时获取数据
// 监听URL参数变化
useEffect(() => {
  fetchTopics();
}, [topicIdFromUrl]);

  const toggleTopic = (topicId: string) => {
    setExpandedTopics(prev => ({
      ...prev,
      [topicId]: !prev[topicId]
    }));
    
  };

  const handleTopicAction = async(action: string, topicId: string) => {
    switch(action) {
      case 'delete':
        setTopics(prev => prev.filter(t => t.id !== topicId));
        break;
      case 'duplicate':
        // Implement duplicate logic
        break;
      case 'rename':
        // Implement rename logic
      case 'addCopy':
        // 如果没有内容,设置默认的文档结构
        const novelcopy = {
          type: "doc",
          content: [
            {
              type: "heading",
              attrs: { level: 1 },
              content: [{ type: "text", text: "新文案" }]
            },
            {
              type: "paragraph",
              content: [{ type: "text", text: "内容简介" }]
            },
            { type: "paragraph" },
            { type: "paragraph" }
          ]
        };
        const copy ={
          "id":"",
          "title":"新文案",
          "intro":"",
          "topic_id":topicId,
          "status":"文案编辑中",
          "script_num":0,
          "finished_script_num":0,
          "cjsj":new Date(),
          "content": JSON.stringify(novelcopy)
        }
        const token = localStorage.getItem('token')
        const response = await fetch('/api/copy', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(copy)
        });
        if (!response.ok) {
          throw new Error('添加失败');
        }
        const data = await response.json();
        toast({
          title: '添加成功',
          description: '文案已成功添加',
        })
    
        localStorage.removeItem("novel-content")
        // 修复：先更新 topics，然后基于新的 topics 更新 filteredTopics
        const updatedTopics = topics.map(t => ({
          ...t,
          copies: t.id === topicId ? [...t.copies, data] : t.copies
        }));
        
        setTopics(updatedTopics);
        
        // 无论是否有topicIdFromUrl，都同步更新filteredTopics
        if (topicIdFromUrl) {
          const updatedFilteredTopics = updatedTopics.filter(topic => topic.id === topicIdFromUrl);
          setFilteredTopics(updatedFilteredTopics);
        } else {
          // 如果没有过滤条件，filteredTopics应该与topics保持一致
          setFilteredTopics(updatedTopics);
        }
        
        // 自动选择新创建的文案
        fetchCopy(data.id, topicId);
        
        break;

      default:
        break;
    }
  };

  const handleCopyAction = async (action: string, copyId: string) => {
    switch(action) {
      case 'delete':
        const confirmed = window.confirm('确定要删除吗？');
        if(confirmed){
          const token = localStorage.getItem('token');
          
          // 立即检查并清理当前显示的文案（在API调用前）
          const isCurrentCopy = copy && copy.id === copyId;
          if (isCurrentCopy) {
            setCopy(undefined); // 清空当前文案状态
            setSelectedItem(null); // 清空选中状态
            setCopyLoading(false); // 停止加载状态
          }
          
          // 立即清理localStorage中的相关缓存（在API调用前）
          const lastViewed = localStorage.getItem('lastViewedCopy');
          if (lastViewed) {
            try {
              const { copyId: lastCopyId } = JSON.parse(lastViewed);
              if (lastCopyId === copyId) {
                localStorage.removeItem('lastViewedCopy');
                localStorage.removeItem('novel-content');
                localStorage.removeItem('html-content');
                localStorage.removeItem('markdown');
              }
            } catch (error) {
              // 如果解析失败，清理所有相关缓存
              localStorage.removeItem('lastViewedCopy');
              localStorage.removeItem('novel-content');
              localStorage.removeItem('html-content');
              localStorage.removeItem('markdown');
            }
          }
          
          try {
            const response = await fetch(`/api/copy/${copyId}`, {
              method: 'DELETE',
              headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
              }
            });
            
            if (!response.ok) {
              throw new Error('删除失败');
            }
            
            // 在 handleCopyAction 函数的删除逻辑中
            // 更新topics状态
            setTopics(prev => {
              const newTopics = prev.map(topic => ({
                ...topic,
                copies: topic.copies.filter(c => c.id !== copyId)
              }));
              
              // 检查删除后是否还有文案存在
              const hasAnyCopies = newTopics.some(topic => topic.copies.length > 0);
              
              // 如果删除的是当前文案且还有其他文案，选择第一个可用的文案
              if (isCurrentCopy && hasAnyCopies) {
                // 使用setTimeout确保状态更新完成后再选择新文案
                setTimeout(() => {
                  for (const topic of newTopics) {
                    if (topic.copies.length > 0) {
                      fetchCopy(topic.copies[0].id, topic.id);
                      break;
                    }
                  }
                }, 100);
              }
              
              return newTopics;
            });
            
            // 添加：同步更新 filteredTopics
            if (topicIdFromUrl) {
              setFilteredTopics(prev => 
                prev.map(topic => ({
                  ...topic,
                  copies: topic.copies.filter(c => c.id !== copyId)
                }))
              );
            } else {
              // 如果没有过滤条件，filteredTopics 应该与 topics 保持一致
              setFilteredTopics(prev => 
                prev.map(topic => ({
                  ...topic,
                  copies: topic.copies.filter(c => c.id !== copyId)
                }))
              );
            }
            toast({
              title: '删除成功',
              description: '文案已成功删除',
            });
          } catch (error) {
            // 如果删除失败，恢复状态（如果之前清理了的话）
            console.error('删除失败:', error);
            toast({
              title: '删除失败',
              description: '请稍后重试',
              variant: 'destructive'
            });
          }
        }
        break;
      case 'duplicate':
        // Implement duplicate logic
        break;
      case 'share':
        // Implement share logic
        break;
      case 'rename':
        // Implement rename logic
        break;
      default:
        break;
    }
  };


  const handleTopicClick = (e: React.MouseEvent, topicId: string) => {
    e.stopPropagation();
    setSelectedItem({ type: 'topic', topicId });
    toggleTopic(topicId);
  };

  const handleCopyClick = (e: React.MouseEvent, topicId: string, copyId: string) => {
    e.stopPropagation();
    localStorage.removeItem("novel-content")
    // 保存当前查看的文案信息
    localStorage.setItem('lastViewedCopy', JSON.stringify({ topicId, copyId }));
    fetchCopy(copyId, topicId);
  };

  const getSelectedItemInfo = () => {
    if (!selectedItem) return null;

    const topic = topics.find(t => t.id === selectedItem.topicId);
    if (!topic) return null;

    if (selectedItem.type === 'copy' && selectedItem.copyId) {
      const copy = topic.copies.find(c => c.id === selectedItem.copyId);
      return copy ? { topic, copy } : null;
    }

    return { topic };
  };

  // 添加更新 pxh 的函数
const updateTopicsPxh = async (topics: Topic[]) => {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch('/api/notion/topicPx', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({ topics })
    });

    if (!response.ok) {
      throw new Error('更新失败');
    }
  } catch (error) {
    console.error('更新排序失败:', error);
    toast({
      title: '更新排序失败',
      description: '请稍后重试',
      variant: 'destructive'
    });
  }
};

 // 添加更新 pxh 的函数
 const updateCopiesPxh = async (copies: Copy[]) => {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch('/api/notion/copyPx', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({ copies })
    });

    if (!response.ok) {
      throw new Error('更新失败');
    }
  } catch (error) {
    console.error('更新排序失败:', error);
    toast({
      title: '更新排序失败',
      description: '请稍后重试',
      variant: 'destructive'
    });
  }
};

  const onDragEnd = async (result: DropResult) => {
    const { source, destination, type } = result;

    if (!destination) return;

    // 保存当前状态以便回滚
    const previousTopics = [...topics];

    if (type === 'TOPIC') {
      const newTopics = Array.from(topics);
    const [removed] = newTopics.splice(source.index, 1);
    newTopics.splice(destination.index, 0, removed);
    
    // 更新所有话题的 pxh
    const updatedTopics = newTopics.map((topic, index) => ({
      ...topic,
      pxh: index + 1
    }));
    
    try {
      // 先更新UI
      setTopics(updatedTopics);
      // 调用接口
      await updateTopicsPxh(updatedTopics);
    } catch (error) {
      // 失败时回滚到之前的状态
      setTopics(previousTopics);
    }
    } else if (type === 'COPY') {
      const sourceTopic = topics.find(topic => topic.id === source.droppableId);
  const destTopic = topics.find(topic => topic.id === destination.droppableId);

  if (!sourceTopic || !destTopic) return;

  const sourceCopies = Array.from(sourceTopic.copies);
  const destCopies = Array.from(destTopic.copies || []);
  const [removed] = sourceCopies.splice(source.index, 1);

  if (source.droppableId === destination.droppableId) {
    // 同一话题内拖拽
    sourceCopies.splice(destination.index, 0, removed);
    // 更新 copies 的 pxh
    const updatedCopies = sourceCopies.map((copy, index) => ({
      ...copy,
      pxh: index + 1
    }));
    const newTopics = topics.map(topic => 
      topic.id === sourceTopic.id ? { ...topic, copies: updatedCopies } : topic
    );
    try {
      // 先更新UI
      const newTopics = topics.map(topic => 
        topic.id === sourceTopic.id ? { ...topic, copies: updatedCopies } : topic
      );
      setTopics(newTopics);
      // 调用接口
      await updateCopiesPxh(updatedCopies);
    } catch (error) {
      // 失败时回滚
      setTopics(previousTopics);
   
    }
  } else {
    const updatedCopy = {
      ...removed,
      topic_id: destTopic.id
    };
    // 跨话题拖拽
    destCopies.splice(destination.index, 0, updatedCopy);
    // 更新两个话题的 copies 的 pxh
    const updatedSourceCopies = sourceCopies.map((copy, index) => ({
      ...copy,
      pxh: index + 1
    }));
    const updatedDestCopies = destCopies.map((copy, index) => ({
      ...copy,
      pxh: index + 1
    }));
    
    try {
      // 先更新UI
      const newTopics = topics.map(topic => {
        if (topic.id === sourceTopic.id) {
          return { ...topic, copies: updatedSourceCopies };
        }
        if (topic.id === destTopic.id) {
          return { ...topic, copies: updatedDestCopies };
        }
        return topic;
      });
      setTopics(newTopics);
      // 调用接口
      const allCopies = [...updatedSourceCopies, ...updatedDestCopies];
      await updateCopiesPxh(allCopies);
    } catch (error) {
      // 失败时回滚
      setTopics(previousTopics);
      toast({
        title: '更新失败',
        description: '已恢复原有顺序',
        variant: 'destructive'
      });
    }
      }
    }


    
  };


  return (
    <DragDropContext onDragEnd={onDragEnd}>
      <div className="flex h-screen">
         <NotionSidebar
          searchDialogOpen={searchDialogOpen}
          setSearchDialogOpen={setSearchDialogOpen}
          searchTerm={searchTerm}
          searchResults={searchResults}
          handleSearch={handleSearch}
          topics={filteredTopics}
          loading={loading}
          expandedTopics={expandedTopics}
          selectedItem={selectedItem}
          handleTopicClick={handleTopicClick}
          handleCopyClick={handleCopyClick}
          handleTopicAction={handleTopicAction}
          handleCopyAction={handleCopyAction}
          onDragEnd={onDragEnd}
        />
        
           {/* 右侧内容区域 */}
        <div className="flex-1 p-8 h-screen overflow-y-auto">
          <div className="flex flex-col gap-4">
            {/* 面包屑导航 */}
            {getSelectedItemInfo() && (
              <Breadcrumb className="mb-4 bg-gray-50 p-3 rounded-lg shadow-sm">
                <BreadcrumbList>
                  <BreadcrumbItem>
                    <BreadcrumbLink href="#" className="flex items-center text-gray-600 hover:text-rose-600 font-medium transition-colors">
                      <span className="text-left">我的项目</span>
                    </BreadcrumbLink>
                  </BreadcrumbItem>
                  <BreadcrumbSeparator>
                    <Slash className="h-4 w-4 text-gray-400" />
                  </BreadcrumbSeparator>
                  <BreadcrumbItem>
                    <BreadcrumbLink href="#" className="flex items-center text-gray-600 hover:text-rose-600 font-medium transition-colors">
                      <span className="text-left">{getSelectedItemInfo()?.topic.name}</span>
                    </BreadcrumbLink>
                  </BreadcrumbItem>
                  {getSelectedItemInfo()?.copy && (
                    <>
                      <BreadcrumbSeparator>
                        <Slash className="h-4 w-4 text-gray-400" />
                      </BreadcrumbSeparator>
                      <BreadcrumbItem>
                        <BreadcrumbLink href="#" className="flex items-center text-gray-600 hover:text-rose-600 font-medium transition-colors">
                          <span className="text-left">{getSelectedItemInfo()?.copy?.title}</span>
                        </BreadcrumbLink>
                      </BreadcrumbItem>
                    </>
                  )}
                </BreadcrumbList>
              </Breadcrumb>
            )}
          </div>

          {/* 页面内容将显示在这里 */}
          <div className="min-h-[calc(100vh-12rem)]">
            {copyLoading ? (
              <div className="flex justify-start items-center h-64">
                {/* <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div> */}
              </div>
            ) : copy ? (
              <div className="flex justify-start w-full">
                <TailwindAdvancedEditor 
                  key={copy?.id} // 添加 key 属性
                  copy={copy}
                  saveCopy={saveCopy}
                />
              </div>
            ) : (
              <div className="flex flex-col items-center justify-center h-64 text-center">
                <div className="flex items-center justify-center h-64 text-gray-500">
                  {topicIdFromUrl && filteredTopics.length > 0 && filteredTopics[0].copies.length === 0 ? (
                    <div className="text-center">
                      <p className="text-lg mb-2">暂无文案</p>
                      <p className="text-sm">当前主题下还没有文案内容</p>
                    </div>
                  ) : (
                    <p>请选择一个文案开始编辑</p>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </DragDropContext>
  );
}

// 主组件用 Suspense 包裹
export default function Page() {
  return (
    <Suspense fallback={
      <div className="flex h-screen">
        <div className="w-80 border-r bg-gray-50">
          <div className="p-4">
            <Skeleton className="h-8 w-full mb-4" />
            <Skeleton className="h-6 w-3/4 mb-2" />
            <Skeleton className="h-6 w-1/2 mb-2" />
            <Skeleton className="h-6 w-2/3" />
          </div>
        </div>
        <div className="flex-1 p-8">
          <Skeleton className="h-8 w-1/3 mb-4" />
          <Skeleton className="h-64 w-full" />
        </div>
      </div>
    }>
      <NotionPageContent />
    </Suspense>
  );
}